package SportsBot::CCC;

use strict;
use LWP::Simple;

# Returns string: the 
sub getLeagueTable
{
    # The Football League Championship (CCC; Coca-Cola Championship)
    #
    # Table URL: http://www.football-league.premiumtv.co.uk/page/DivisionalLeagueTable/0,,10794~20077,00.html

    my $input = get("http://www.football-league.premiumtv.co.uk/page/DivisionalLeagueTable/0,,10794~20077,00.html");
    $input =~ s/[\n\r\t]//g;
    $input =~ s/^.*<tbody>(.*)<\/tbody>.*$/$1/;
    $input =~ s/<td[^>]*>/<td>/g;
    $input =~ s/<\/?a[^>]*>//g;
    $input =~ s/<\/tr>/<\/tr>\n/g;
    $input =~ s/<\/?tr[^>]*>//g;
    $input =~ s/<\/td><td>/ || /g;
    $input =~ s/\d+ \|\| ([A-Z])/$1/g;
    $input =~ s/<\/?td[^>]*>//g;
    my @lines = split(/\n/, $input);

    my ($full, $mini, $counter, $rowclass);
    $counter = 1;

    $full = <<EOF;
{| cellpadding="5" cellspacing="0" class="standingstable"
|- align="center" class="standingssection"
| colspan="10" | '''[[w:Football League Championship|Coca-Cola Football League Championship]]'''
|- class="standingsheader"
| Pos || Team || Pld || W || D || L || F || A || GD || Pts
EOF
    $mini = <<EOF;
{| border=1 cellpadding=3 cellspacing=0 style="margin: 1em 1em ; background: #f9f9f9; border: 1px #aaa solid; border-collapse: collapse; font-size: 95%;"    
|- style="background: #e9e9e9"   
! Pos !! Team !! Pld !! W-D-L !! GD !! Pts
EOF
    foreach (@lines) {
        if ($counter > 0 && $counter < 3) {
            # Premier League
        }
        if ($counter > 2 && $counter < 7) {
            # League Championship Playoffs
        }
        if ($counter > 21) {
            # League One
        }
        if ($counter < 11) {
            $mini .= "|-\n| $counter || " . miniaturizeRow($_) . "\n";
        }
        $rowclass = ($counter & 1 ? "standingsrow" : "standingsrow2");
        $full .= "|- class=\"$rowclass\"\n| $counter || class=\"team\" | $_\n";
        $counter++;
    }
    chop $full; chop $mini;
    my $formatted = <<EOF;
<noinclude>
$full
|}
</noinclude><includeonly>
$mini
|}

[[Template:CCC|Full Football League Table]]
</includeonly>
<small>Last updated: {{subst:#time:F j, Y g:ia}} UTC</small>
EOF
    return $formatted;
}

# Takes a standings table row and shrinks it down for the miniature version
# arg:row     - a standings table row
# return      - a shortened standings table row
sub miniaturizeRow
{
    # Regular row: Pos | Team | Pld | Win | Draw | Loss | G. For | G. Against | G. Diff | Pts
    # Shorter row: Pos | Team | Pld | W-D-L | G. Diff | Pts
    my $row = shift;
    $row =~ s/^([^\|]*) \|\| (\d+) \|\| (\d+) \|\| (\d+) \|\| (\d+) \|\| \d+ \|\| \d+ \|\| ([\d\-]+) \|\| (\d+)$/$1 \|\| $2 \|\| $3-$4-$5 \|\| $6 \|\| $7/g;
    return $row;
}

1;

